package com.shujia.flink.soure

import java.util.Properties

import org.apache.flink.api.common.serialization.SimpleStringSchema
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer

object Demo4ReadKafka {
  def main(args: Array[String]): Unit = {

    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    /**
      * 并行度一般和kafka的分区数对应，多了也没用，  同一个分区只能被一个组内的一个消费者消费
      *
      */
    env.setParallelism(2)

    val properties = new Properties()
    properties.setProperty("bootstrap.servers", "master:9092,node1:9092,node2:9092")
    properties.setProperty("group.id", "test")

    /**
      * flink消费kafkas数据的source
      *
      * 无界流
      *
      */

    val kafkaConsumer: FlinkKafkaConsumer[String] = new FlinkKafkaConsumer[String]("flume", new SimpleStringSchema(), properties)

    kafkaConsumer.setStartFromEarliest() // 尽可能从最早的记录开始
    //    kafkaConsumer.setStartFromLatest()        // 从最新的记录开始
    //    kafkaConsumer.setStartFromTimestamp(...)  // 从指定的时间开始（毫秒）
    //    kafkaConsumer.setStartFromGroupOffsets()  // 默认的方法


    //使用过kafkasource
    val kafkaDS: DataStream[String] = env.addSource(kafkaConsumer)


    kafkaDS
      .flatMap(_.split(","))
      .map(word => (word, 1))
      .keyBy(_._1)
      .sum(1)
      .print()


    env.execute()

  }

}
